package com.hm.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hm.reggie.common.CustomException;
import com.hm.reggie.entity.Category;
import com.hm.reggie.entity.Dish;
import com.hm.reggie.entity.Setmeal;
import com.hm.reggie.mapper.CategoryMapper;
import com.hm.reggie.service.CategoryService;
import com.hm.reggie.service.DishService;
import com.hm.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    /**
     * 更具id删除分类、
     * 删除钱检查套餐和菜品
     * @param ids
     */
    @Override
    public void remove(Long ids) {
        //查询菜品Dish里是否关联了分类，有则返回异常
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<Dish>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,ids);
        int dishcount = dishService.count(dishLambdaQueryWrapper);
        if (dishcount > 0) {
            throw new CustomException("分类关联了"+dishcount+"个菜品，无法删除");
        }

        //查询套餐Setmeal里是否关联了分类，有则返回异常
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<Setmeal>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,ids);
        int setmealcount = setmealService.count(setmealLambdaQueryWrapper);
        if (setmealcount > 0) {
            throw new CustomException("分类关联了"+setmealcount+"个套餐，无法删除");
        }

        //删除分类
        super.removeById(ids);
    }
}
